package com.example.yskjproject.utils;

import android.annotation.SuppressLint;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * DateUtils
 * <p>
 * 作者：zx
 * 创建时间：2024/5/16
 */
public class DateUtils {

    public static long daysBetween(Calendar startDate, Calendar endDate) {
        // 将两个日期都设置为与时间的午夜（00:00:00.000）对齐
        startDate.set(Calendar.HOUR_OF_DAY, 0);
        startDate.set(Calendar.MINUTE, 0);
        startDate.set(Calendar.SECOND, 0);
        startDate.set(Calendar.MILLISECOND, 0);

        endDate.set(Calendar.HOUR_OF_DAY, 0);
        endDate.set(Calendar.MINUTE, 0);
        endDate.set(Calendar.SECOND, 0);
        endDate.set(Calendar.MILLISECOND, 0);

        // 计算两个日期之间的毫秒数
        long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
        // 将毫秒数转换为天数
        return diff / (24 * 60 * 60 * 1000);
    }


    public static  Calendar getNowData(String time){
        String str = "2012-5-27";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar calendar = Calendar.getInstance();
        assert date != null;
        calendar.setTime(date);
        return calendar;
    }

    @RequiresApi(api = Build.VERSION_CODES.S)
    public static boolean compareTime(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串解析为LocalDateTime对象
        LocalDateTime specifiedTime = LocalDateTime.parse(date, formatter);
        // 获取当前系统时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 计算两个时间之间的间隔
        Duration duration = Duration.between(specifiedTime, currentTime);

        // 判断时间间隔是否大于24小时（即86400秒）
        if (duration.toSeconds() > 86400) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * string转成时间戳
     * @param timeString
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static long stringToTimeStamp(String timeString) {
        try {
            String format = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(timeString);
            assert date != null;
            return date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
